package com.musiklegal;




import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;



import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Gallery;
//import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class OnlineC extends Activity {
	final String []menu = {Settings.cari,Settings.def};
	final String []met = {"Top Download","New Release"};
	ProgressDialog dialog;
	//ListView lvm;
	HttpClient mlist;
	HttpGet get;
	HttpResponse mresp ;
	HttpEntity merclist;
	SAXParserFactory spf;
	SAXParser sp;
	XMLReader xr;
	AlertDialog.Builder alert;
	MerchantParser mparse;
	CatalogueParser cp;
	static List<MerchantEntity> merch=new ArrayList<MerchantEntity>();;
	static List<DataSong> catl=new ArrayList<DataSong>();;
	int offset=1;
	TextView tv;
	String method;
	Gallery gal;
	static int post;
	Handler h;
	MerchantAdapter adapter;
	AlertDialog alertDialog;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        h = new Handler();
        alertDialog = new AlertDialog.Builder(this).create();
		alertDialog.setTitle("Error");
		alertDialog.setMessage(Settings.gakonek);
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() { 
			public void onClick(DialogInterface dialog, int which) {
			finish();
			}
		});
		alertDialog.setIcon(R.drawable.oc2);
		
		new Thread(new Runnable(){

			public void run() {
				h.post(new Runnable(){

					public void run() {
						// TODO Auto-generated method stub
						showDialog(0);
					}});
				if(MusikLegal.internet(getApplicationContext())){
				     merch.clear();
				     catl.clear();
				     //gal = (Gallery) findViewById(R.id.gallery1);
			       
			     
			        try{
			        	catl.clear();
						mlist = new DefaultHttpClient(); 
						get = new HttpGet("http://secure.musiklegal.com/?action=merchant&method=info&app=AD");
						mresp = mlist.execute(get);

						merclist = mresp.getEntity();
						spf = SAXParserFactory.newInstance();
						sp = spf.newSAXParser();
						xr = sp.getXMLReader();
						
						mparse = new MerchantParser();
						xr.setContentHandler(mparse);
						xr.parse(retrieveInputStream(merclist));
						
						}
				        catch (Exception e) {
				        	h.post(new Runnable(){

								public void run() {
									// TODO Auto-generated method stub
									Toast.makeText(getApplicationContext(), Settings.gakonek, Toast.LENGTH_SHORT).show();
						        	finish();
								}});
				        	
				        }
				        
				        h.post(new Runnable(){

							public void run() {
								// TODO Auto-generated method stub
								Merchant();
							}});
						
					
					
			        }
			        else
			        {
				        h.post(new Runnable(){

							public void run() {
								// TODO Auto-generated method stub
								alertDialog.show();
							}
				        	
				        });
						
			        }
				h.post(new Runnable(){

					public void run() {
						// TODO Auto-generated method stub
						removeDialog(0);
					}});
			}}).start();
        
	}
	
	public void onResume()
	{
		if(!MusikLegal.internet(getApplicationContext()))
		{
			finish();
		}
		super.onResume();
	}
	
	void Merchant()
	{
		 
		
        setContentView(R.layout.merchant);
        
        alert =  new AlertDialog.Builder(this);
        //lvm=(ListView)findViewById(R.id.MercView);
        adapter = new MerchantAdapter(this,merch);
        gal = (Gallery) findViewById(R.id.gallery1);
        gal.setAdapter(adapter);
//        gal.setOnItemClickListener(new OnItemClickListener(){
//
//			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
//					long arg3) {
//				Toast.makeText(getApplicationContext(), merch.get(arg2).name +" Clicked", Toast.LENGTH_SHORT).show();
//				
//			}});
       
        
        //lvm.setAdapter(adapter);
        //lvm.setTextFilterEnabled(true);
       
//        lvm.setOnItemLongClickListener(new OnItemLongClickListener(){
//
//			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
//					int arg2, long arg3) {
//				MerchantEntity m = merch.get(arg2);
//				MainMenu.defaultMerchant = m;
//				SharedPreferences.Editor editor = MusikLegal.mPreferences.edit();
//				editor.putString("Catalogue", m.toString());
//				editor.commit();
//				Toast.makeText(getApplicationContext(), m.name+" set as default", Toast.LENGTH_SHORT).show();
//				
//				return true;
//			}});
        
        gal.setOnItemClickListener(new OnItemClickListener() 
        {
          public void onItemClick(AdapterView<?> parent, View view,final int position, long id) 
          {
        	  
        	  new Thread(new Runnable(){

				public void run() {
					//showDialog(0);
					h.post(new Runnable(){

						public void run() {
							  Browseby.pos=position;
				        	  Browseby.apikey = merch.get(position).id+"-"+merch.get(position).key;
				        	  Browseby.imurl=merch.get(position).imgUrl;
				        	  Browseby.name=merch.get(position).name;
				        	  startActivity(new Intent(getApplicationContext(),Browseby.class));
				        	
							
						}});
				}}).start();
        	  
	        	
        		
        	
          }
          
        });
        
        gal.setOnItemLongClickListener(new OnItemLongClickListener(){

			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					final int position, long arg3) {
				
				alert.setTitle( Settings.joption );
				alert.setIcon(R.drawable.oc2);
	        	alert.setItems( menu , new DialogInterface.OnClickListener() {
	                public void onClick(DialogInterface dialog, int item) {
	                	
	                	switch(item)
	                	{
	                		case 0:

	                    		try 
	                    		{
	                        		catl.clear();
	                        		String p = "http://secure.musiklegal.com/?action=catalogue&method=get&api_key="+merch.get(position).id+"-"+merch.get(position).key+"&limit=25&offset=";
	                        		get = new HttpGet(p+1);
	                        		CatalogueList.merchant = merch.get(position);
	                        		
	                        		CatalogueList.addres = new Address("http://secure.musiklegal.com/?action=catalogue&method=get&api_key="+merch.get(position).id+"-"+merch.get(position).key+"&limit=25",1,"");
	            					mresp = mlist.execute(get);
	            					merclist= mresp.getEntity();
	            	        		cp = new CatalogueParser();
	            	        		xr.setContentHandler(cp);
	            	        		xr.parse(retrieveInputStream(merclist));
	            	        		OnlineC.catl.addAll(cp.catl);
	            				} 
	                    		catch (ClientProtocolException e) {
	            					
	            					e.printStackTrace();
	            					finish();
	            				} catch (IOException e) {
	            					
	            					e.printStackTrace();
	            					finish();
	            				}
	            				catch (SAXException e) {
	            					
	            					e.printStackTrace();
	            					finish();
	            					
	            				}
	            				
	                    		CatalogueList.thismerchant =merch.get(position);
	                    		Browseby.apikey = merch.get(position).id+"-"+merch.get(position).key;
	            			
	            	        Intent i = new Intent(getApplicationContext(), CatalogueList.class);
	            			startActivity(i);
	                		break;
	                		case 1:
	                			
	                			MerchantEntity m = merch.get(position);
	            				MainMenu.defaultMerchant = m;
	            				SharedPreferences.Editor editor = MusikLegal.mPreferences.edit();
	            				editor.putString("Catalogue", m.toString());
	            				editor.putString("defkey", merch.get(position).id+"-"+merch.get(position).key);
	            				editor.putString("defimg", merch.get(position).imgUrl);
	            				editor.putString("defname", merch.get(position).name);
	            				editor.commit();
	            				MainMenu.defpos=position;
	            				Toast.makeText(getApplicationContext(), m.name+" set as default", Toast.LENGTH_SHORT).show();
	            				
	                			
	                		break;
	                	
	                	}
	                	
	                
	                }});
	        	alert.setCancelable(true);
	        	alert.create();
	        	alert.show();
				
				return true;
			}});
        
        
        
	}

	protected Dialog onCreateDialog(int id) {
        switch (id) {
              case 0: {
                    dialog = new ProgressDialog(this);
                    dialog.setMessage("Loading...");
                    dialog.setIndeterminate(true);
                    dialog.setCancelable(true);
                    return dialog;                   
              }
        }
        return null;
  }
	public void onDestroy()
	{
		System.gc();
		if(adapter!=null)
			adapter.clear();
		super.onDestroy();
	}
	
	private InputSource retrieveInputStream(HttpEntity httpEntity) {
        InputSource insrc = null;
        try {
              insrc = new InputSource(httpEntity.getContent());
        } catch (Exception e) {
        }
        return insrc;
  }	
}
	